import java.io.*;
import java.net.*;
public class ServerThread extends Thread
{
    // The Server that spawned us
    private Server server;
    // The Socket connected to our client
    private Player player;
    // The DataOutputStream for the client
    private DataOutputStream dout;
    // Constructor.
    public ServerThread (Server server, Player player, DataOutputStream dout)
    {
	// Save the parameters
	this.server = server;
	this.player = player;
	this.dout = dout;
	// Start up the thread
	start ();
    }


    // This runs in a separate thread when start() is called in the
    // constructor.
    public void run ()
    {
	try
	{
	    // Create a DataInputStream for communication; the client
	    // is using a DataOutputStream to write to us
	    DataInputStream din = player.getDataInputStream ();
	    // Over and over, forever ...
	    while (true)
	    {
		// ... read the next message ...
		String message = din.readUTF ();

		// a check done to see if we're creating the user
		if (message.startsWith ("/m"))
		{
		    String[] components = message.split(" ");
		    server.messageTo(player, components[1], message.substring(message.indexOf(" ", 3), message.length()));
		}
		else
		{
		    // ... tell the world ...
		    System.out.println ("Sending " + message);
		    // ... and have the server send it to all clients
		    //server.sendToAll( message );
		    server.sendToAll (player.getUsername() + ": " + message);
		}
	    }
	}
	catch (EOFException ie)
	{
	    // This doesn't need an error message
	}
	catch (IOException ie)
	{
	    // This does; tell the world!
	    ie.printStackTrace ();
	}
	finally
	{
	    // The connection is closed for one reason or another,
	    // so have the server dealing with it
	    server.removeConnection (player);
	}
    }
}
